﻿using Microsoft.Extensions.Logging;
using NetCore.IRepository.Order_LayerwinDingmachineEquipment;
using NetCore.Model.Enity;
using NetCore.Model.VeiwModels;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NetCore.Repository.Order_LayerwinDingmachineEquipment
{
    public class Order_layerwindingmachineequipmentRepository : BaseRepository<OrderLayerwindingmachineequipment>, IOrder_layerwindingmachineequipmentRepository
    {
        private readonly ILogger<Order_layerwindingmachineequipmentRepository> _logger;

        public Order_layerwindingmachineequipmentRepository(ILogger<Order_layerwindingmachineequipmentRepository> Logger)
        {
            _logger = Logger;
        }

        /// <summary>
        /// 获取条数
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<int> GetTotalNumber(int type = 0)
        {
            int count = 0;
            if (type == 0)
                count = await Db.Queryable<OrderLayerwindingmachineequipment>().Select(x => x.Id).CountAsync();
            else
                count = await Db.Queryable<OrderLayerwindingmachineequipment>().Where(x => x.ShiftId == type).Select(x => x.Id).CountAsync();
            return count;
        }

        /// <summary>
        /// 缓存添加班次比例
        /// </summary>
        /// <returns></returns>
        public async Task<GetShiftProportionResult> AddShiftProportionRedis()
        {
            try
            {
                //总条数
                int total_count = await Db.Queryable<OrderLayerwindingmachineequipment>().Select(x => x.Id).CountAsync();
                //早班条数
                int morningShift_count = await Db.Queryable<OrderLayerwindingmachineequipment>().Where(x => x.EquipmentId == 5).Select(x => x.Id).CountAsync();
                //中班条数
                int middleShift_count = await Db.Queryable<OrderLayerwindingmachineequipment>().Where(x => x.EquipmentId == 6).Select(x => x.Id).CountAsync();
                //晚班条数
                int eveningShift_count = await Db.Queryable<OrderLayerwindingmachineequipment>().Where(x => x.EquipmentId == 7).Select(x => x.Id).CountAsync();
                GetShiftProportionResult getShiftProportionResult = new GetShiftProportionResult()
                {
                    Total_count = total_count,
                    MorningShift_count = morningShift_count,
                    MiddleShift_count = middleShift_count,
                    EveningShift_count = eveningShift_count,
                    MorningShiftPercentage = (morningShift_count / total_count) + "%",
                    MiddleShiftPercentage = (middleShift_count / total_count) + "%",
                    EveningShiftPercentage = (eveningShift_count / total_count) + "%"
                };
                return getShiftProportionResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
                return null;
            }
        }

        /// <summary>
        /// 统计指定月份每天数据
        /// </summary>
        /// <param name="year">年</param>
        /// <param name="month">月</param>
        /// <param name="equipmentId">设备id</param>
        /// <returns></returns>
        public async Task<List<DayCount>> Month_StatisticsDailyData(Month_StatisticsDailyDataFrom statisticsDailyDataFrom)
        {
            List<DayCount> dayCounts = new List<DayCount>();
            try
            {
                //初始化时间-----如果是查询当月那么 time就是 DateTime.Now
                DateTime time = new DateTime(statisticsDailyDataFrom.Year, statisticsDailyDataFrom.Month, 1, 1, 1, 1);
                //获取1月天数
                var days = (time.AddMonths(1) - time).Days;
                //转成时间数组
                var dayArray = Enumerable.Range(1, days).Select(it => Convert.ToDateTime(time.ToString("yyyy-MM-" + it))).ToList();
                //初始化DateTime
                var queryableLeft = Db.Reportable(dayArray).ToQueryable<DateTime>();
                //初始化查询表
                var queryableRight = Db.Queryable<OrderLayerwindingmachineequipment>();
                //设置条件
                queryableRight = queryableRight.WhereIF(statisticsDailyDataFrom.Equipmentid != 0, it => it.EquipmentId == statisticsDailyDataFrom.Equipmentid);
                queryableRight = queryableRight.WhereIF(statisticsDailyDataFrom.Userid != 0, it => it.Userid == statisticsDailyDataFrom.Userid);
                queryableRight = queryableRight.WhereIF(statisticsDailyDataFrom.Shiftid != 0, it => it.ShiftId == statisticsDailyDataFrom.Shiftid);
                //查询
                var list = await Db.Queryable(queryableLeft, queryableRight, JoinType.Left,
                    (x1, x2) => x1.ColumnName.Date == x2.ProductionTime.Date)
                    .GroupBy((x1, x2) => x1.ColumnName)
                    .Select((x1, x2) => new
                    {
                        count = SqlFunc.AggregateSum(SqlFunc.IIF(x2.Id > 0, 1, 0)),
                        day = x1.ColumnName.Day
                    }).ToListAsync();

                #region 初始化返回数据

                foreach (var li in list)
                {
                    DayCount dayCount = new DayCount()
                    {
                        Count = li.count,
                        Day = li.day
                    };
                    dayCounts.Add(dayCount);
                }

                #endregion 初始化返回数据

                return dayCounts.OrderBy(st => st.Day).ToList();//根据day排序
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
                return null;
            }
        }

        /// <summary>
        /// 统计指定年份每月数据
        /// </summary>
        /// <param name="year_StatisticsDailyDataFrom"></param>
        /// <returns></returns>
        public async Task<List<MonthCount>> Year_StatisticsDailyData(Year_StatisticsDailyDataFrom year_StatisticsDailyDataFrom)
        {
            List<MonthCount> monthCounts = new List<MonthCount>();
            try
            {
                //初始化时间-----如果是查询当月那么 time就是 DateTime.Now
                DateTime time = new DateTime(year_StatisticsDailyDataFrom.Year, 1, 1, 1, 1, 1);
                //转成时间数组
                var dayArray = Enumerable.Range(1, 12).Select(it => Convert.ToDateTime(time.ToString("yyyy-" + it))).ToList();
                //初始化DateTime
                var queryableLeft = Db.Reportable(dayArray).ToQueryable<DateTime>();
                /*var queryableLeft = Db.Reportable((ReportableDateType)Enum.ToObject(typeof(ReportableDateType), year_StatisticsDailyDataFrom.reportabledatetype)).ToQueryable<DateTime>(); //生成月份*/
                //ReportableDateType.MonthsInLast1yea 表式近一年月份 并且queryable之后还能在where过滤
                //声名表
                var queryableRight = Db.Queryable<OrderLayerwindingmachineequipment>();
                //设置条件
                queryableRight = queryableRight.WhereIF(year_StatisticsDailyDataFrom.Equipmentid != 0, it => it.EquipmentId == year_StatisticsDailyDataFrom.Equipmentid);
                queryableRight = queryableRight.WhereIF(year_StatisticsDailyDataFrom.Userid != 0, it => it.Userid == year_StatisticsDailyDataFrom.Userid);
                queryableRight = queryableRight.WhereIF(year_StatisticsDailyDataFrom.Shiftid != 0, it => it.ShiftId == year_StatisticsDailyDataFrom.Shiftid);
                //月份和表JOIN
                var list = await Db.Queryable(queryableLeft, queryableRight, JoinType.Left, (x1, x2) => x2.ProductionTime.ToString("yyyy-MM") == x1.ColumnName.ToString("yyyy-MM"))
                .GroupBy((x1, x2) => x1.ColumnName)
                .Select((x1, x2) => new
                {
                    count = SqlFunc.AggregateSum(SqlFunc.IIF(x2.Id > 0, 1, 0)), //null的数据要为0所以不能用count
                    date = x1.ColumnName.ToString("yyyy-MM")
                }
                ).ToListAsync();

                #region 初始化返回数据

                foreach (var li in list)
                {
                    MonthCount monthCount = new MonthCount()
                    {
                        Count = li.count,
                        Date = li.date
                    };
                    monthCounts.Add(monthCount);
                }

                #endregion 初始化返回数据

                return monthCounts.OrderBy(st => st.Date).ToList();//根据day排序
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
                return null;
            }
        }

        /// <summary>
        /// 添加层绕机设备订单信息
        /// </summary>
        /// <returns></returns>
        public async Task<long> AddOrder_LayerwindingmachineEquipmentr_Bak(OrderLayerwindingmachineequipmentrBak orderLayerwindingmachineequipmentrBak)
        {
            long id = await Db.Insertable(new OrderLayerwindingmachineequipmentrBak()
            {
                DiscNumber = orderLayerwindingmachineequipmentrBak.DiscNumber,
                EquipmentId = orderLayerwindingmachineequipmentrBak.EquipmentId,
                RawmaterialId = orderLayerwindingmachineequipmentrBak.RawmaterialId,
                OrderDrawingequipmentId = orderLayerwindingmachineequipmentrBak.OrderDrawingequipmentId,
                ShiftId = orderLayerwindingmachineequipmentrBak.ShiftId,
                Weight = orderLayerwindingmachineequipmentrBak.Weight,
                Userid = orderLayerwindingmachineequipmentrBak.Userid,
                WoodenPalletNo = orderLayerwindingmachineequipmentrBak.WoodenPalletNo,
                ProductionTime = orderLayerwindingmachineequipmentrBak.ProductionTime,
                RunTime = orderLayerwindingmachineequipmentrBak.RunTime,
                ProductionproductId = orderLayerwindingmachineequipmentrBak.ProductionproductId,
                Qualifiedproducts = orderLayerwindingmachineequipmentrBak.Qualifiedproducts
            }).ExecuteReturnBigIdentityAsync();
            return id;
        }

        /// <summary>
        /// 获取订单信息
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public async Task<long> GetOredrInfo(int userid, int productionproductid, DateTime starttime, DateTime endtime)
        {
            try
            {
                var count = await Db.Queryable<OrderLayerwindingmachineequipmentrBak>().Select(x => x).Where(x => x.Userid == userid &&
                              x.ProductionproductId == productionproductid &&
                              x.Qualifiedproducts == 1 &&
                              x.ProductionTime.Hour >= starttime.Hour &&
                              x.ProductionTime.Minute >= starttime.Minute &&
                              x.ProductionTime.Second >= starttime.Second &&
                              x.ProductionTime.Hour <= endtime.Hour
                              )
                .WhereIF(endtime.Minute > 0, x => x.ProductionTime.Minute == endtime.Minute)
                .WhereIF(endtime.Second > 0, x => x.ProductionTime.Second == endtime.Second)
                .CountAsync();

                return count;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return 0;
            }
        }
    }
}